<template>
  <div ref="scrollerRef" class="scroller" @scroll="onScroll">
    <template v-for="(source, index) in list">
      <slot v-bind="{ source, index }"></slot>
    </template>
  </div>
</template>
<script lang="ts" setup>
import { animateScrollTo } from "@/utils/common";
import { debounce } from "lodash-es";

defineProps({
  sizeKey: {
    type: String,
    default: "message"
  },
  loading: {
    type: Boolean,
    default: false
  },
  list: {
    type: Array as PropType<any[]> | PropType<any[]>,
    default: () => []
  }
});

const emit = defineEmits(["scroll", "scroll-start", "scroll-end", "is-scroll-bottom"]);

const scrollerRef = ref<HTMLDivElement>();
const onScroll = debounce(() => {
  emit("scroll", scrollerRef.value);
  if (scrollerRef.value) {
    const { scrollTop, scrollHeight, clientHeight } = scrollerRef.value!;

    if (scrollHeight > clientHeight) {
      // 确定产生滚动区
      emit("is-scroll-bottom", scrollTop >= scrollHeight - clientHeight - 20);
    } else {
      emit("is-scroll-bottom", true);
    }
  }
}, 50);
const scrollToBottom = () => {
  if (scrollerRef.value) {
    animateScrollTo(scrollerRef.value, scrollerRef.value?.scrollHeight || 9999999999999, 500);
  }
};
defineExpose({
  scrollerRef,
  scrollToBottom
});
</script>
<style lang="scss" scoped>
.scroller {
  height: 100%;
  width: 100%;
  overflow-x: hidden;
  overflow-y: scroll;
  touch-action: pan-y;
  -webkit-overflow-scrolling: touch;
}
</style>
